package com.xj.socket.tcp.nio.server;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 此类封装了一个只处理连接的Selector
 * 
 * @author xiajun
 * 
 */
public class ConnectionSelector implements Runnable {
	private final static Logger log = Logger.getLogger(ConnectionSelector.class);
	private Selector selector = null;

	public ConnectionSelector() throws IOException {
		this.selector = Selector.open();
	}

	/**
	 * 线程运行函数，循环监听客户端连接事件
	 */
	public void run() {
		try {
			while (true) {
				log.debug("---------------");
				if (this.selector.select() <= 0) {
					continue;
				}
				Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
				Iterator<SelectionKey> it = selectedKeys.iterator();
				while (it.hasNext()) {
					log.debug("-----------");
					SelectionKey key = it.next();
					it.remove();
					if (key.isAcceptable()) {
						SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
						channel.configureBlocking(false);
						ReadWriteSelector rws = ReadWritePool.getReadWriteSelector();
						synchronized (rws.lock) {
							rws.getSelector().wakeup();
							channel.register(rws.getSelector(), SelectionKey.OP_READ);
						}
						log.info("客户端" + channel.socket().getInetAddress() + "连接上来...");
						if (!rws.isRunning()) {
							log.debug("ConnectionSelector ReadWriteSelector没有开启" + rws.getSelectorName());
							new Thread(rws).start();
							rws.setIsRunning(true);
						}
					}
				}
			}
		} catch (IOException e) {

		}
	}

	/**
	 * 返回处理连接的Selector
	 * 
	 * @return Selector
	 */
	public Selector getSelector() {
		return this.selector;
	}
}
